<template>
  <el-dialog
    :visible="isShow"
    width="600px"
    class="register"
    :show-close="false"
  >
    <div slot="title" class="title">用户注册</div>
    <el-form :model="form" :rules="rules" label-width="80px" ref="form">
        <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'/uploads'"
          :show-file-list="false"
          name="image"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
         
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
         <el-row >
             <el-col :span="16" >
                 <el-input v-model="form.code"></el-input>
             </el-col>
             <el-col :span="7" :offset="1">
                 <img :src="codeUrl" alt="" class="image" @click="refreshCode">
             </el-col>
         </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
          <el-row >
             <el-col :span="16" >
                 <el-input v-model="form.rcode"></el-input>
             </el-col>
             <el-col :span="7" :offset="1">
                 <el-button @click="getRcode" :disabled="totalTime < 60" class="rcode">
                   获取用户验证码<span v-if="totalTime !=60">{{ totalTime }}秒</span>
                  </el-button>
             </el-col>
         </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="getLogin">注册</el-button>
      <el-button @click="isShow = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { sendsms, register} from '@/api/login.js'
var timeId = null
export default {
  data() {
    return {
      totalTime:60,
      codeUrl:process.env.VUE_APP_URL + '/captcha?type=sendsms',
      baseUrl:process.env.VUE_APP_URL,
      isShow: false,
      imageUrl:'',
      form:{
         avatar:'',   //头像
         username:'', //用户名
         email:'',    //邮箱
         phone:'',    //电话
         password:'', //密码
         code:'',     //图形码
         rcode:'',    //验证码
      },
      rules:{
        avatar:[{required:true, message:"请输入头像",trigger:"change" }],
         username:[{required:true, message:"请输入用户名", trigger:"change"}],
         email:[
           {required:true, message:"请输入邮箱", trigger:"change"},
           {validator:(rule,value,callback) =>{
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if(reg.test(value)){
                callback()
              }else{
                callback("请正确输入邮箱")
              }
           },
           trigger:"change"}
         ],
         phone:[
           {required:true, message:"请输入电话", trigger:"change"},
           {validator:(rule,value,callback) =>{
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if(reg.test(value)){
                callback()
              }else{
                callback("请正确输入电话号码")
              }
           },
           trigger:"change"}
           ],
         password:[{required:true, message:"请输入密码", trigger:"change"}],
         code:[{required:true, message:"请输入图形码", trigger:"change"}],
         rcode:[{required:true, message:"请输入验证码", trigger:"change"}],  
      }
    };
  },

  watch: {
    "isShow"(newVal){
      if(newVal == false){
        this.$refs.form.resetFields()
        this.imageUrl='';
        clearInterval(timeId)
        this.totalTime= 60
      }
    }
  },
  methods: {
    // 上传成功后  
      handleAvatarSuccess(res, file) {
        window.console.log(file)
        this.imageUrl = URL.createObjectURL(file.raw);
        this.form.avatar = res.data.file_path;
        //表单部分验证
        this.$refs.form.validateField(['avatar'], error=>{
            window.console.log("出现就有error就不通过,为空就通过",error)
        })
      },

    //  上传前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 或PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
       
      //  全局验证
      getLogin(){
        this.$refs.form.validate(result =>{
          if(!result){
            this.message.error("注册失败,请完整填写信息")
          }else{
            // 验证通过调用接口
            register(this.form).then(res =>{
              window.console.log("注册结果",res);
              //if(res.data.code == 200){
                this.$message.success("注册成功")
                this.isShow = false
             // }else{
             //   this.$message.error("注册失败")
             // }
            })
          }
        })
      },
     
    //  获取手机验证码
      getRcode(){
        let _IsPass = 0;
        this.$refs.form.validateField(['code','phone'] ,error =>{
         if(!error){
           _IsPass++
         }
        })
        if(_IsPass == 2){
          // 验证通过
          this.totalTime--
            timeId = setInterval(() => {
              this.totalTime--
              if(this.totalTime <=0){
                clearInterval(timeId)
                this.totalTime= 60
              }
            }, 1000);
          sendsms({
            code:this.form.code,
            phone:this.form.phone
          }).then(res =>{
           window.console.log(res);
            this.$message.success(res.data.captcha+'');
          })

        }
      },

      // 点击刷新图形码
      refreshCode(){
        this.codeUrl = process.env.VUE_APP_URL + '/captcha?type=sendsms&t=' + Date.now()
      }
    } 
  
}
</script>

<style lang="less">
.register {
  .el-dialog__header {
    padding: 0px;
  }
  .title {
    height: 53px;
    line-height: 53px;
    color: #fff;
    text-align: center;
    background: linear-gradient(to right, #00c7fc, #0098fa);

    .el-dialog__header {
      padding: 0px;
    }
  }
  .footer {
    text-align: center;
  }
  .avatar-uploader{
      text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .image{
      width:100%;
  }
  .rcode{
    padding: 10px;
  }
}
</style>
